<?php
require_once'config.php';
require_once'weixin_info.php';
$order_sn = $_GET['order_sn'];
if(!isset($order_sn)||empty($order_sn)){
	$back_info = ['code' => 405, 'msg' => '未定义的订单号'];
    echo json_encode($back_info);
    die;
}

$goods_order = $mysql->query("select * from dyspw_goods_order where ordernum =" . $order_sn);
$check = $goods_order->fetch_all(MYSQLI_ASSOC);

$shop_id = $check[0]['shop_id'];

$shop_sql = $mysql->query("select * from dyspw_member where id =" . $shop_id);
$shop_info = $shop_sql->fetch_all(MYSQLI_ASSOC);

$shop_son_id = $shop_info[0]['shop_son_id'];
$branch_store_id = $shop_info['branch_store_id'];
if(!isset($shop_id)||empty($shop_id)){
	$back_info = ['code' => 405, 'msg' => '未定义的商家信息'];
    echo json_encode($back_info);
    die;
}
// print_r($check);
$goods_sql = $mysql->query("select * from dyspw_goods where id = {$check[0]['goods_id']}");
$goods_info = $goods_sql->fetch_all(MYSQLI_ASSOC);
if (!empty($check)) {
	if($check[0]['shop_id'] == $_SESSION['Member_info'][0]['id'] || $check[0]['shop_id'] == $shop_son_id){
		$time = time()-$check[0]['uptime'];
		if(($time<10)&&$check[0]['uptime']){
			$back_info = ['code' => 200, 'msg' => '核销成功'];
				echo json_encode($back_info);
				exit;
		}else{
			if ($check[0]['state']==4) {
					$back_info = ['code' => 400, 'msg' => '订单已过期'];
					echo json_encode($back_info);
					exit;

			}elseif($check[0]['state']==3){
					$back_info = ['code' => 400, 'msg' => '订单已核销，无法二次核销'];
					echo json_encode($back_info);
					exit;

			}elseif($check[0]['state']==1){


					$Up1 = "Update dyspw_goods_order set state = 3, uptime = '".time()."' where id = ".$check[0]['id'];
					// $Up2 = "Update dyspw_goods_order set uptime = '".time()."' where id = ".$check[0]['id'];
					$update1 = mysqli_query($mysql, $Up1);
					// $update2 = mysqli_query($mysql, $Up2);
					if (!$update1) {
						$back_info = ['code' => 400, 'msg' => '更新订单信息失败'];
						echo json_encode($back_info);exit;
					}
					//核销成功后添加商户收支明细，给当前商户余额增值
					if($check[0]['order_type'] == 'waimai'){
						$service_fee = $check[0]['money'] * 0.006;
						$operation_fee = $check[0]['money'] * 0.03;
						$income_money = $check[0]['money'] - $service_fee - $operation_fee;
					}else{
						$income_money = $check[0]['Price'] - ($check[0]['Price'] * 0.03);
					}

					// if($check[0]['shop_id'] == 701 && $check[0]['order_type'] != 'waimai'){
					// 	$income_money = 200 * 0.87;
					// }

					$time = time();
					$mysql->query("INSERT INTO dyspw_shop_detailed (u_id,o_id,goods_id,goods_name,o_money,goods_img,u_name,u_avatar,income_money, hexiao_time,type,branch_store_id) VALUES ('{$shop_id}', '{$check[0]['id']}', '{$check[0]['goods_id']}', '{$goods_info[0]['title']}', '{$check[0]['money']}', '{$goods_info[0]['img']}', '{$shop_info[0]['username']}', '{$shop_info[0]['avatar']}', '{$income_money}',{$time}, '1','{$branch_store_id}')");
					if(!empty($branch_store_id)){
						$mysql->query("Update dyspw_member set balance = balance + {$income_money} where id = {$branch_store_id}");
					}else{
						$mysql->query("Update dyspw_member set balance = balance + {$income_money} where id = {$shop_id}");
					}
					if($check[0]['guide_uid'] != 0 && !empty($check[0]['guide_uid'])){
						$guide_sql = $mysql->query("select * from dyspw_shop_guide where guide_id = {$check[0]['guide_uid']}");
						$guide = $guide_sql->fetch_all(MYSQLI_ASSOC);
						if(!empty($guide)){
							$mysql->query("Update dyspw_shop_guide set guide_money = guide_money + {$check[0]['money']} where guide_id = {$check[0]['guide_uid']}");
						}
					}

					//订单核销分账
					$oid=$check[0]['id'];
					$goods_order = $mysql->query('select a.*,b.merchant_num,b.merchant_key from dyspw_goods_order as a inner join dyspw_member as b on a.shop_id = b.id where a.id = '.$oid);
					$orderInfo = $goods_order->fetch_assoc();
					$sharing_state=1;
					//参与分账的订单
					if($orderInfo['profit_sharing'] == 'Y'){
						//是否参与过分账并且成功
						if($orderInfo['sharing_state'] == '1'){
							//账号绑定商户号
							if($orderInfo['merchant_num']){
								include_once ('include/global.config.php');
								$wxConfig=$globalConfig['wx'];
								$wxPayment=new wxPayment($wxConfig);

								$orderCode=time().mt_rand(1000,9999);
								$money=$orderInfo['money'];
								$result=$wxPayment->profitShare([
									'sub_mch_id'=>$orderInfo['merchant_num'],//特约商户号
									'transaction_id'=>$orderInfo['transaction_id'],
									'out_order_no'=>$orderCode,
									'receivers'=>[
										['type'=>'MERCHANT_ID',  'account'=>$wxConfig['mchId'],  "amount"=>intval($money*0.03),"description"=>"分到服务商"]
									]
								]);
								//分账状态
								$sharing_state=$result['status'] ? 0 : 2;
								$remark=json_encode($result['data'],JSON_UNESCAPED_UNICODE);
								//记录分账日志
								$order_id = $sharing_state ? '' : $result['data']['order_id'];
								$print_sql="INSERT INTO separate_log(oid,money,create_time,out_order_no,order_id,status,remark) VALUES('$oid','$money',".time().",
		'$orderCode','$order_id','$sharing_state','$remark') ON DUPLICATE KEY UPDATE money='$money',out_order_no='$orderCode',order_id='$order_id',status='$sharing_state',create_time = ".time().",remark = '$remark'";
								$mysql->query($print_sql);
							}
						}
					}

					$back_info = ['code' => 200, 'msg' => '核销成功'];
					echo json_encode($back_info);
					exit;

			}else{
					$back_info = ['code' => 400, 'msg' => '默认失败'];
					echo json_encode($back_info);
					exit;
			}
		}
	}else{
		$back_info = ['code' => 400, 'msg' => '商家信息不匹配'];
    	exit(json_encode($back_info));
	}

} else {
	$back_info = ['code' => 400, 'msg' => '无此订单或商家信息不匹配'];
    exit(json_encode($back_info));



}
